import { createSlice } from '@reduxjs/toolkit'
import { http } from '@/utils/index'
// let obj = window
const userStore = createSlice({
  name: 'user',
  initialState: {
    // token: obj?.localStorage.getItem('token'),
    token: localStorage.getItem('token') || '',
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      localStorage.setItem('token', action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      state.userInfo = {}
      state.token = ''
      localStorage.removeItem('token')
    },
  },
})
// 异步方法封装
const fetchLogin = (loginForm) => {
  // console.log(loginForm)
  return async (dispatch) => {
    const res = await http.post('/authorizations', loginForm)
    if (res) {
      dispatch(setToken(res.data.token))
    }
  }
}
const fetchUserInfo = () => {
  return async (dispatch) => {
    await http
      .get('/user/profile')
      .then((res) => {
        dispatch(setUserInfo(res.data))
      })
      .catch((err) => {
        return err
      })
  }
}

const { setToken, setUserInfo, clearUserInfo } = userStore.actions
export { fetchLogin, fetchUserInfo, clearUserInfo }
const userReducer = userStore.reducer
export default userReducer
